import Vue from 'vue'
import axios from 'axios'
import { Notice } from 'iview'

const requestMap = {}

// response interceptor
axios.interceptors.request.use(request => {
  let key
  // abort the same post request
  if (/POST|PUT|DELETE/.test(request.method)) {
    key = `${request.method}${request.url}${JSON.stringify(request.body)}`
    // abort the existed request
    if (key && requestMap[key]) {
      key = null
      setTimeout(() => {
        request.abort()
      })
    } else {
      requestMap[key] = request
    }
  }
  return request
})

axios.interceptors.response.use(response => {
  // delete current request in the map
  const request = response.request
  let key
  if (/POST|PUT|DELETE/.test(request.method)) {
    key = `${request.method}${request.url}${JSON.stringify(request.body)}`
    delete requestMap[key]
  }
  if (response.status === 401) {
    Notice.error({
      title: Vue.t('http.error.E401')
    })
    return response
  }
  if (response.status === 403) {
    Notice.error({
      title: Vue.t('http.error.E403')
    })
    return response
  }
  if (response.status === 404) {
    return response
  }
  if (response.status === 500) {
    Notice.error({
      title: Vue.t('http.error.E500')
    })
    return response
  }
  return response
})
